<?php

namespace app\common\logic;

use app\school_api\model\ClassStudentDistribution;
use app\school_api\model\grade\GradeClass;
use app\school_api\model\StudentParent;
use app\school_api\model\StudentUser;
use think\Cache;
use think\Config;
use think\Db;
use app\common\{
    controller\Frontend,
    logic\Wework,
    logic\SendMessage
};

use app\admin\model\{
    School,
    school\Department,
    student\Student,
    student\Parents,
    school\DepartmentAdmins
};
use think\Exception;

class Dao
{
    public $result = [];

    public static $baseUrl = 'https://qyapi.weixin.qq.com/';


    //*********************************部门 handle start*******************************************************//

    /**
     * 添加部门
     * @param string|null $msg_id [description]
     */
    public function addDepartment(string $msg_id = null)
    {
        //添加或编辑需要请求部门列表
        $res = Wework::schoolDepartmentGet(Wework::getAccessToken(), $msg_id);
        if (empty($res['errcode']) && !empty($res['departments'])) {
            //新增
            $data = [];
            foreach ($res['departments'] as $item) {
                $data[] = [
                    'id' => $item['id'],
                    'parentid' => $item['parentid'],
                    'type' => $item['type'],
                    'name' => $item['name'],
                    'open_group_chat' => $item['open_group_chat'] ?? 0,
                    'department_admins' => json_encode($item['department_admins']),
                    'creattime' => time()
                ];
            }
            return Department::insertAll($data) && true;
        } else {
            $this->result = $res;
            return false;
        }
    }


    /**
     * 刷新部门列表-家校通讯录
     * @return [string] [description]
     */
    public function refreshDepartment(string $msg_id = null)
    {
        //获取部门
        $res = Wework::schoolDepartmentGet(Wework::getBookAccessToken(), $msg_id);


        $data = [];
        $department_admins = [];
        $wechat_standard = [91, 92, 93, 94];
        $grade = Db::name('grade')->field('id,name,wechat_id')->select();
        $grade_wechat_id = array_column($grade, 'wechat_id');

        if (!empty($res['departments'])) {
            $insert = [];
            $update = [];
            $wechat_id = [];
            $time = time();
            $school_campus_id = campus_id(1);
            $year_id = year_id(1);
            foreach ($res['departments'] as $k => $v) {


                //1班级 2年级
                if ($v['type'] == 2 && isset($v['standard_grade']) && in_array($v['standard_grade'], $wechat_standard)) {

                    dump($v);
                    if (in_array($v['id'], $grade_wechat_id)) {
                        //更新
                        array_push($update, "WHEN {$v['id']} THEN '{$v['name']}'");
                        array_push($wechat_id, $v['id']);
                    } else {
                        //插入
                        array_push($insert, " ('{$v['name']}',{$school_campus_id},{$year_id},1,{$time},{$v['id']})");
                    }
                }
            }


            die;
            if ($insert) {
                $insert = implode(',', $insert);
                $sql = "INSERT INTO `fa_grade` (`name`,`school_campus_id`,`year_id`,`class_hour`,`createtime`,`wechat_id`)  VALUES {$insert}";

            }

            if ($update) {
                $wechat_id = implode(',', $wechat_id);
                $update = implode(' ', $update);
                $sql = "UPDATE `fa_grade` SET name = (CASE `wechat_id` {$update} END), `updatetime` = {$time} WHERE `wechat_id` IN ({$wechat_id})";
            }


            $result = Db::query($sql);
        }


    }


    /**
     * ok
     * 刷新部门列表-非家校通讯录
     * @return [string] [description]
     */
    public function departmentListGet(string $msg_id = null, $is_update = true)
    {
        //获取部门
        $res = Wework::departmentListGet(Wework::getBookAccessToken(), $msg_id);
        if (isset($res['errcode']) && (int)$res['errcode'] === 0) {
            if (empty($res['department'])) {
                $this->result = $res;
                return '没有部门被同步';
            } else {
                if (!$is_update) {
                    return $res['department'];
                }
                //当前数据
                $department = Db::name('school_department')->field('wechat_id,id')->select();

                $department_ext = array_column($department, 'wechat_id');
                $insert = [];
                $update = [];
                $time = time();
                $wechat_id = [];
                $school_campus_id = campus_id(1);
                foreach ($res['department'] as $item) {
                    if (in_array($item['id'], $department_ext)) {
                        array_push($update, "WHEN {$item['id']} THEN '{$item['name']}'");
                        array_push($wechat_id, $item['id']);
                    } else {
                        array_push($insert, " ('{$item['parentid']}',{$school_campus_id},'{$item['name']}',{$item['id']},1,{$time})");
                    }
                }


                if ($insert) {
                    $insert = implode(',', $insert);
                    $sql = "INSERT INTO `fa_school_department` (`pid`,`school_campus_id`,`name`,`wechat_id`,`sort`,`createtime`)  VALUES {$insert}";
//                    dump($sql,1,'insert');
                    Db::query($sql);
                }

                if ($update) {
                    $wechat_id = implode(',', $wechat_id);
                    $update = implode(' ', $update);
                    $sql = "UPDATE `fa_school_department` SET name = (CASE `wechat_id` {$update} END), `updatetime` = {$time} WHERE `wechat_id` IN ({$wechat_id})";
//                    dump($sql,1,'update');
                    Db::query($sql);
                }

                return true;
            }

        }
    }


    //同步成员列表
    public function userList()
    {
        $school_campus_id = campus_id(1);

        $user = Db::name('user')->field('id,username,mobile,UserId')->select();
        $user_mobile = array_column($user, 'mobile');
        $user_id = array_column($user, 'id');
        $user_mobile = array_combine($user_mobile, $user_id);


        $user_ext = array_column($user, 'UserId');
        $department = Db::name('school_department')->field('id,wechat_id')->select();

        $password = '99d7db228a2f27a2ceaae81f42f8e73b';
        $salt = 'fZetmE';
        $insert_user = [];
        $update_user = ['username' => [], 'nickname' => [], 'avatar' => [], 'position' => []];
        $update_user_id = [];
        $time = time();
        $wechat_id = [];
        $user_id = [];

        $ext = [];
        foreach ($department as $dep) {
            $result = Wework::userListGet(Wework::getBookAccessToken(), $dep['wechat_id']);
            if (!isset($result['errcode']) && $result['errcode'] !== 0 && empty($result['userlist'])) {
                continue;
            }

            foreach ($result['userlist'] as $item) {
                if (in_array($item['userid'], $ext)) {
                    continue;
                }

                array_push($ext, $item['userid']);
                if (in_array($item['userid'], $user_ext)) {
                    array_push($update_user['username'], "WHEN '{$item['userid']}' THEN '{$item['name']}'");
                    array_push($update_user['nickname'], "WHEN '{$item['userid']}' THEN '{$item['name']}'");
                    array_push($update_user['avatar'], "WHEN '{$item['userid']}' THEN '{$item['avatar']}'");
                    array_push($update_user['position'], "WHEN '{$item['userid']}' THEN '{$item['position']}'");
                    array_push($wechat_id, "'{$item['userid']}'");
                } else {
                    if (isset($user_mobile[$item['mobile']])) {
                        array_push($user_id, "'{$user_mobile[$item['mobile']]}'");
                        array_push($update_user_id, "WHEN '{$user_mobile[$item['mobile']]}' THEN '{$item['userid']}'");
                    } else {
                        array_push($insert_user, "({$school_campus_id},0,'{$item['name']}','{$item['name']}','{$password}','{$salt}','{$item['mobile']}','{$item['avatar']}',{$item['gender']},'{$item['userid']}','{$item['position']}','2',{$time},'normal')");
                    }
                }
            }
        }


        if ($insert_user) {
            $insert_user = implode(',', $insert_user);
            $sql = "INSERT INTO `fa_user` (`school_campus_id`,`group_id`,`username`,`nickname`,`password`,`salt`,`mobile`,`avatar`,`gender`,`UserId`,`position`,`origin_info`,`createtime`,`status`)  VALUES {$insert_user}";
//                    dump($sql,1,'insert');
            Db::query($sql);
        }

        if ($update_user && $wechat_id) {
            $wechat_id = implode(',', $wechat_id);
            $username = implode(' ', $update_user['username']);
            $nickname = implode(' ', $update_user['nickname']);
            $avatar = implode(' ', $update_user['avatar']);
            $position = implode(' ', $update_user['position']);
            $sql = "UPDATE `fa_user` SET username = (CASE `UserId` {$username} END),nickname = (CASE `UserId` {$nickname} END),avatar = (CASE `UserId` {$avatar} END),position = (CASE `UserId` {$position} END), `origin_info` = '2',`updatetime` = {$time} WHERE `UserId` IN ({$wechat_id})";

//            dump($sql,1,'$update_user');
            Db::query($sql);
        }


        if ($update_user_id && $user_id) {
            $user_id = implode(',', $user_id);
            $update_user_id = implode(' ', $update_user_id);
            $sql = "UPDATE `fa_user` SET UserId = (CASE `id` {$update_user_id} END),`updatetime` = {$time} WHERE `UserId` IN ({$user_id})";
//            dump($sql,1,'$update_user_id');
            Db::query($sql);
        }


    }


    public function userlead(int $page = 1)
    {
        $user = Db::name('user')->whereNotNull('UserId')->field('UserId,id')->page($page, 100)->select();
        if (!$user) {
            exit('没有数据可处理');
        }
        $department = Db::name('school_department')->whereNotNull('wechat_id')->column('wechat_id,id');
        $department_relation = Db::name('school_department_relation')->field('id,user_id,department_id')->select();


        $school_campus_id = campus_id(1);
        $year_id = campus_id(1);
        $semester_id = campus_id(1);
        $insert_dep = [];
        $update_dep = ['department_lead' => [], 'wechat_dep_id' => [], 'wechat_user_id' => []];
        $update_dep_id = [];
        $time = time();

        foreach ($user as $k => $item) {
            $result = Wework::getUserInfo(Wework::getBookAccessToken(), $item['UserId']);

            if (empty($result['department'])) {
                continue;
            }

            $depArray = array_combine($result['department'], $result['is_leader_in_dept']);

            foreach ($depArray as $key => $dep) {
                if (isset($department[$key])) {
                    $is = false;
                    foreach ($department_relation as $rel => $relation) {
                        if ($relation['user_id'] == $item['id'] && $relation['department_id'] == $department[$key]) {
                            array_push($update_dep['department_lead'], "WHEN {$relation['id']} THEN '{$dep}'");
                            array_push($update_dep['wechat_dep_id'], "WHEN {$relation['id']} THEN {$key}");
                            array_push($update_dep['wechat_user_id'], "WHEN {$relation['id']} THEN '{$result['userid']}'");
                            array_push($update_dep_id, $relation['id']);
                            $is = true;
                            unset($department_relation[$rel]);
                            continue;
                        }
                    }


                    if (!$is) {
                        array_push($insert_dep, "({$department[$key]},{$item['id']},{$school_campus_id},{$year_id},{$semester_id},{$time},'{$dep}',{$key},'{$result['userid']}')");
                    }
                }
            }

            unset($user[$k]);
        }


        if ($insert_dep) {
            $insert_dep = implode(',', $insert_dep);
            $sql = "INSERT INTO `fa_school_department_relation` (`department_id`,`user_id`,`school_campus_id`,`year_id`,`semester_id`,`createtime`,`department_lead`,`wechat_dep_id`,`wechat_user_id`)  VALUES {$insert_dep}";
//                    dump($sql,1,'insert');
            Db::query($sql);
        }

        if ($update_dep && $update_dep_id) {
            $update_dep_id = implode(',', $update_dep_id);
            $department_lead = implode(' ', $update_dep['department_lead']);
            $wechat_dep_id = implode(' ', $update_dep['wechat_dep_id']);
            $wechat_user_id = implode(' ', $update_dep['wechat_user_id']);
            $sql = "UPDATE `fa_school_department_relation` SET department_lead = (CASE `id` {$department_lead} END),wechat_dep_id = (CASE `id` {$wechat_dep_id} END),wechat_user_id = (CASE `id` {$wechat_user_id} END),`updatetime` = {$time} WHERE `id` IN ({$update_dep_id})";

//            dump($sql,1,'update');
            Db::query($sql);
        }


    }


    /**
     * 刷新部成员-通讯录
     * @return [string] [description]
     */
    public function departmenUserListGet(string $msg_id = null)
    {
        //获取部门
        $res = Wework::departmenUserListGet(Wework::getBookAccessToken(), $msg_id);
        return $res;
        if (isset($res['errcode']) && (int)$res['errcode'] === 0) {
            if (empty($res['departments'])) {
                $this->result = $res;
                return '没有部门被同步';
            } else {
                $data = [];
                $department_admins = [];
                foreach ($res['departments'] as $item) {
                    array_push($data, [
                        'id' => $item['id'],
                        'parentid' => $item['parentid'],
                        'name' => $item['name'],
                        'department_admins' => json_encode($item['department_admins']),
                        'open_group_chat' => $item['open_group_chat'] ?? '',
                        'group_chat_id' => $item['group_chat_id'] ?? '',
                        'type' => $item['type'],
                        'createtime' => time()
                    ]);


                    //添加班主任
                    /*foreach ($item['department_admins'] as $val) {
                        array_push($department_admins,[
                            'department_id' =>$item['id'],
                            'userid'        =>$val['userid'],
                            'type'          =>$val['type'],
                            'subject'       =>$val['id'] ?? '',
                        ]);
                    }*/
                }

                /*$Department = new Department;
                $DepartmentAdmins = new DepartmentAdmins;

                $DepartmentWhere = [];
                $DepartmentAdminsWhere = [];
                $where = [];
                if ($msg_id) {
                    //操作某个部门
                    $DepartmentWhere = ['id'=>$msg_id];
                    $DepartmentAdminsWhere = ['department_id'=>$msg_id];
                }


                $Department->where($DepartmentWhere)->delete(true);
                $DepartmentAdmins->where($DepartmentAdminsWhere)->delete(true);

                if ($data) {
                    $Department->saveAll($data);
                }
                if ($department_admins) {
                    $DepartmentAdmins->saveAll($department_admins);
                }*/

                return $data;
            }
        }
    }

    /**
     * 删除部门
     * @param string $msg_id [description]
     * @return [type]         [description]
     */
    public function deleteDepartment(string $msg_id)
    {
        Department::where(['id' => $msg_id])->delete();
        DepartmentAdmins::where(['id' => $msg_id])->delete();
    }


    //*********************************部门 handle end*******************************************************//


    //*********************************学生 handle start*******************************************************//

    /**
     * 添加学生
     * @param string $msg_id [description]
     */
    public function addStudent(string $msg_id)
    {
        logs(111, '注册111');

        $res = Wework::schoolUserGet($msg_id);
        logs($res, '注册');

        if (empty($res['errcode']) && !empty($res['student'])) {

//                $parent = [];
//                $createUserInfo = createUserInfo($res['student']['student_userid']);
//                $data = [
//                    'student_userid' => $res['student']['student_userid'],
//                    'department' => implode(',', $res['student']['department']),
//                    'name' => $res['student']['name'],
//                    // 'card'              => $createUserInfo['card'],
//                    'person_ids' => $createUserInfo['person_ids'],
//                    'avatar' => $createUserInfo['avatar'],
//                    'createtime' => time()
//                ];
//
//                //添加家长
//                foreach ($res['student']['parents'] as $item) {
//                    array_push($parent, [
//                        'student_userid' => $res['student']['student_userid'],
//                        'parent_userid' => $item['parent_userid'],
//                        'relation' => $item['relation'],
//                        'mobile' => $item['mobile'] ?? '',
//                        'is_subscribe' => $item['is_subscribe'],
//                        'external_userid' => $item['external_userid'] ?? '',
//                        'createtime' => time()
//                    ]);
//                }
//                Student::insert($data); Parents::insertAll($parent);

            try {
                $student_data = [
                    'nickname' => $res['student']['name'],
                    'username' => $res['student']['name'],
                    'wechat_id' => $res['student']['student_userid'],
                ];
                $student_model = new StudentUser();
                $student_model->save($student_data);
                $student_id = $student_model->id;

                if ($res['student']['parents']) {
                    $parents = [];
                    foreach ($res['student']['parents'] as $key => $val) {
                        $parents[] = [
                            'student_userid' => $student_id,
                            'nickname' => $res['student']['name'] . $val['relation'],
                            'relation' => $val['relation'],
                            'is_subscribe' => $val['is_subscribe'],
                            'mobile' => $val['mobile'],
                            'wechat_parent_userid' => $val['parent_userid'],
                            'wechat_student_userid' => $res['student']['student_userid'],
                            'wechat_external_userid' => $val['external_userid'] ?? '',
                        ];

                    }
                    if ($parents) {
                        (new StudentParent())->saveAll($parents);
                    }
                }
                if ($res['student']['department'][0]) {
                    $class = (new GradeClass())->where('wechat_id', $res['student']['department'][0])->find();
                    if ($class) {
                        $class_data = [
                            'campus_id' => campus_id(1),
                            'year_id' => year_id(1),
                            'semester_id' => semester_id(1),
                            'grade_id' => $class['grade_id'],
                            'student_id' => $student_id,
                            'class_id' => $class['id'],
                            'class_num' => '',
                            'remark' => '',
                            'wechat_id' => '',

                        ];
                        (new ClassStudentDistribution())->save($class_data);
                    }
                }
                $student_data = [
                    'user_id' => $student_id,
                    'campus_id' => campus_id(1),
                    'ent_year' => date('Y'),
                    'data_source' => 1,
                    'realname' => $res['student']['name'],
                    'createtime' => time(),
                    'updatetime' => time()
                ];

                (new \app\admin\model\Student())->save($student_data);


            } catch (\Exception $e) {

                logs($e->getMessage(), '666665555');
            }


            return true;

        } else {
            $this->result = $res;
            return false;
        }


    }


    /**
     * 刷新班级学生列表
     * 学生存在则更新 不存在个添加
     * 家长统一删除后再添加
     * @param  [type] $department_id [description]
     * @return [type]                [description]
     */
    public function refreshStudentList($department_id)
    {
        $res = Wework::schoolUserListGet(Wework::getBookAccessToken(), $department_id);
        return $res;
        if (isset($res['errcode']) && (int)$res['errcode'] === 0) {
            if (empty($res['students'])) {
                $this->result = $res;
                return '该年级/班级下没有学生';
            } else {
                $studentData = [];
                $parentsData = [];

                //当前存在的学生
                $exist = Student::where("FIND_IN_SET({$department_id},department)")->column('student_userid');
                foreach ($res['students'] as $item) {

                    if (in_array($item['student_userid'], $exist)) {
                        Student::where('student_userid', $item['student_userid'])->update([
                            'department' => implode(',', $item['department']),
                            'name' => $item['name'],
                        ]);
                    } else {
                        array_push($studentData, [
                            'department' => implode(',', $item['department']),
                            'student_userid' => $item['student_userid'],
                            'name' => $item['name'],
                            'createtime' => time(),
                        ]);
                    }


                    foreach ($item['parents'] as $parents) {
                        array_push($parentsData, [
                            'student_userid' => $item['student_userid'],
                            'parent_userid' => $parents['parent_userid'],
                            'relation' => $parents['relation'],
                            'is_subscribe' => $parents['is_subscribe'],
                            'mobile' => $parents['mobile'],
                            'external_userid' => $parents['external_userid'] ?? '',
                            'createtime' => time(),
                        ]);
                    }

                }


                if ($exist) {
                    Parents::where('student_userid', 'in', $exist)->delete();
                }

                if ($studentData) {
                    Student::insertAll($studentData);
                }

                if ($parentsData) {
                    Parents::insertAll($parentsData);
                }

                return true;
            }
        }
    }


    /**
     * 刷新学生信息
     * @param string $msg_id [description]
     * @return [type]         [description]
     */
    public function refreshStudent(string $msg_id)
    {
        $student = Wework::schoolUserGet(Wework::getAccessToken(), $msg_id);
        if (empty($student['errcode']) && !empty($student['student'])) {

            if (Student::where('student_userid', $student['student']['student_userid'])->value('student_userid')) {
                Student::where('student_userid', $student['student']['student_userid'])->update([
                    'department' => implode(',', $student['student']['department']),
                    'name' => $student['student']['name'],
                ]);
            } else {
                Student::insert([
                    'student_userid' => $student['student']['student_userid'],
                    'department' => implode(',', $student['student']['department']),
                    'name' => $student['student']['name'],
                    'createtime' => time()
                ]);
            }


            $data = [];
            foreach ($student['student']['parents'] as $item) {
                array_push($data, [
                    'student_userid' => $student['student']['student_userid'],
                    'parent_userid' => $item['parent_userid'],
                    'relation' => $item['relation'],
                    'is_subscribe' => $item['is_subscribe'],
                    'mobile' => $item['mobile'],
                    'external_userid' => $item['external_userid'] ?? '',
                    'createtime' => time(),
                ]);
            }

            if ($data) {
                Parents::where('student_userid', $student['student']['student_userid'])->delete();
                Parents::insertAll($data);
            }
        }
    }


    //*********************************学生 handle end*******************************************************//


    //*********************************家长 handle start*******************************************************//


    /**
     * 更新家长信息
     * @param string|null $msg_id [description]
     * @return [type]              [description]
     */
    public function refreshParent(string $msg_id = null)
    {
        $parents = Wework::schoolUserGet($msg_id);
        logs($parents, '家长信息');
        if (empty($parents['errcode']) && !empty($parents['parent'])) {


//            foreach ($parents['parent']['children'] as $children) {
//            try {
//
//                $user_id = (new StudentUser())->where('wechat_id',$parents['parent']['children'][0]['student_userid'])->field('id,nickname')->find();
//                $parentsData[] = [
//                    'nickname'=>$user_id['nickname']??''.$parents['parent']['children'][0]['relation'],
//                    'student_userid'=>$user_id['id']??'',
//                    'wechat_student_userid' => $parents['parent']['children'][0]['student_userid'],
//                    'wechat_parent_userid' => $parents['parent']['parent_userid'],
//                    'relation' => $parents['parent']['children'][0]['relation'],
//                    'is_subscribe' => $parents['parent']['is_subscribe']??'',
//                    'createtime' => time()
//                ];
////            }
//logs($parentsData,'注册数据');
//                (new StudentParent())->where(['parent_userid' => $parents['parent']['parent_userid']])->delete();
//                (new StudentParent())->insertAll($parentsData);
//            }catch (\Exception $e){
//                logs($e->getMessage(),'家长注册信息');
//            }

        }
    }



    //*********************************家长 handle end*******************************************************//


    //*********************************登录 handle end*******************************************************//

    public function getByUser()
    {

    }


    //*********************************登录 handle end*******************************************************//


    //*********************************发送通知 handle start*******************************************************//
    /**
     * 文本消息
     * @return [type] [description]
     */
    public function sendText(string $student_userid, $name, $memo, $start_time, $end_time)
    {
        $confg = config('wework.AgentId');
        $Obj = new SendMessage(Wework::getAccessToken(), $confg);
        $Obj->userid([$student_userid]);
        // $Obj->text("<h2>学生请假通知</h2>\n学生姓名：{$name}\n请假时间：{$start_time}\n结束时间：{$end_time}");
        $Obj->text("学生请假通知\n学生姓名：{$name}\n请假时间：{$start_time}\n结束时间：{$end_time}\n备注：{$memo}");
        $msg = $Obj->send();

        logs(json_encode($msg, 256), '..........学校通知发送结果........', '/dao');
        return $msg;
    }


    /**
     *
     * 文本消息 - 学生通知
     * @return [type] [description]
     */
    public function sendStudentNews($student_userid, $title, $name, $date, $facility_site, $bodyTemperature, $lateStatus, $face)
    {
        $confg = config('wework.AgentId');
        $Obj = new SendMessage(Wework::getAccessToken(), $confg);
        $Obj->userid([$student_userid]);
        $Obj->news(
            "学生{$title}",
            "学生姓名：{$name}\n拍摄时间：" . $date . "\n拍摄位置：{$facility_site}\n{$bodyTemperature}{$lateStatus}",
            $face,
            $face);
        $msg = $Obj->send();

        logs(['result' => json_encode($msg, 256), 'date' => "学生姓名：{$name}\n拍摄时间：" . $date . "\n拍摄位置：{$facility_site}\n{$bodyTemperature}{$lateStatus}"], '..........学校通知发送结果........', '/dao');
        return $msg;
    }













    //----------------------------------------应用消息---------------------------------------------------
    //教师文本消息
    public static function sendTeacherText($touser, $title, $info, $production_id, $origin_id, $appname, $event = '')
    {
        $confg = config("wework.{$appname}");
        $date = date('Y-m-d H:i');
        $http_type = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')) ? 'https://' : 'http://';
        $http_type = $http_type . $_SERVER['SERVER_NAME'];
        if ($event == 1) {
            //活动申请http://hlgzx.zhiyunapi.com/h5/#/pages/cooperation/inspection/detail?type=1&id=38&type2=0
            $url = $http_type . '/h5/#/pages/cooperation/inspection/detail?type=1&id=' . $origin_id;
            $teble = 'user';
        } elseif ($event == 3) {
            //老师请假
            $url = $http_type . '/h5/#/pages/cooperation/inspection/detail?type=2&id=' . $origin_id;
            $teble = 'user';
        } elseif ($event == 4) {
            //调课申请http://hlgzx.zhiyunapi.com/h5/#/pages/cooperation/course/details?type=1&id=7
            $url = $http_type . '/h5/#/pages/cooperation/course/details?type=1&id=' . $origin_id;
            $teble = 'user';
        } elseif ($event == 5) {
            //校园报修http://hlgzx.zhiyunapi.com/h5/#/pages/cooperation/repair/detail?type=2&id=6
            $url = $http_type . '/h5/#/pages/cooperation/repair/detail?id=' . $origin_id;
            $teble = 'user';
        } elseif ($event == 6) {
            //公开课/第二课堂http://hlgzx.zhiyunapi.com/h5/#/pages/cooperation/inspection/detail?type=6&id=26&type2=0
            $url = $http_type . '/h5/#/pages/cooperation/inspection/detail?type=6&id=' . $origin_id;
            $teble = 'user';
        } elseif ($event == 7) {
            //安全隐患http://hlgzx.zhiyunapi.com/h5/#/pages/cooperation/inspection/detail?type=7&id=24&type2=0
            $url = $http_type . '/h5/#/pages/cooperation/inspection/detail?type=7&id=' . $origin_id;
            $teble = 'user';
        } elseif ($event == 8) {
            //物品领用http://hlgzx.zhiyunapi.com/h5/#/pages/cooperation/inspection/detail?type=8&id=47&type2=0
            $url = $http_type . '/h5/#/pages/cooperation/inspection/detail?type=8&id=' . $origin_id;
            $teble = 'user';
        } elseif ($event == 10) {
            //学生请假/考勤http://hlgzx.zhiyunapi.com/h5/#/pages/index/class/detail/leave?id=10
            $url = $http_type . '/h5/#/pages/index/class/detail/leave?id=' . $origin_id;
            $teble = 'student_user';
        } elseif ($event == 15) {
            //购置公物http://hlgzx.zhiyunapi.com/h5/#/pages/cooperation/purchase/details?type=0&id=10
            $url = $http_type . '/h5/#/pages/cooperation/purchase/details?id=' . $origin_id;
            $teble = 'user';
        } elseif ($event == 21) {
            //公文流转http://hlgzx.zhiyunapi.com/h5/#/pages/cooperation/words/detail?type=1&id=286
            $url = $http_type . '/h5/#/pages/cooperation/words/detail?id=' . $origin_id;
            $teble = 'user';
        } elseif ($event == 23) {
            //公务出差http://hlgzx.zhiyunapi.com/h5/#/pages/cooperation/works/details?type=0&id=5
            $url = $http_type . '/h5/#/pages/cooperation/works/details?id=' . $origin_id;
            $teble = 'user';
        } else {
            $url = $http_type . '/h5/#/pages/cooperation/words/detail?id=' . $origin_id;
            $teble = 'user';
        }
        $username = Db::name($teble)->where('id', $production_id)->value('username');
        $touser = Db::name('user')->where('id', 'in', $touser)->column('UserId');
        foreach ($touser as $key => $user) {
            // $msg = [
            //     'touser' => $user,
            //     'msgtype' => 'text',//文本消息
            //     'agentid' => $confg['AgentId'],
            //     'text' => [
            //         'content' => "标题：{$title}\n事由：{$info}.\n时间：{$date}\n申请人：{$username}",
            //     ]
            // ];
            //longer修改，点击推送消息会进入详情页
            $msg = [
                'touser' => $user,
                'msgtype' => 'textcard',//文本卡片消息
                'agentid' => $confg['AgentId'],
                'textcard' => [
                    'title' => $title,
                    'description' => "事由：{$info}.\n时间：{$date}\n申请人：{$username}",
                    'url' => $url,
                ]
            ];

            $_res = \fast\Http::post(self::$baseUrl . "cgi-bin/message/send?access_token=" . Wework::getAppAccessToken($appname), json_encode($msg));
            $res = json_decode($_res, true);
        }
        //return $res;
    }


    //教师请假预警消息
    public static function sendTeacherLeaveNews($touser, $title, $info, $production_id, $origin_id, $appname, $event = '')
    {

        $origin = Db::name('teacher_leave')->where('id', $origin_id)->find();
        $school = Db::name('config')->where('group', 'school')->column('name,value');
        if ($school['teacher_leave_warning'] == '-1') {
            return;
        }
        if (isset($school['teacher_leave_warning']) && $school['teacher_leave_warning'] <= $origin['day']) {
            $confg = config("wework.{$appname}");
            $username = Db::name('user')->where('id', $production_id)->value('username');

            $push = Db::name('config')->where('name', 'teacher_leave_warning_push')->value('value');
            $touser = Db::name('user')->where('id', 'in', $push)->column('UserId');
            if (!$touser) {
                return;
            }

            $msg = [
                'touser' => implode('|', $touser),
                'msgtype' => 'markdown',
                'agentid' => $confg['AgentId'],
                'content' => "`请假消息预警`
                                >人员姓名：<font color=\"info\">{$username}</font> 
                                >开始时间：<font color=\"comment\">" . date('Y-m-d H:i', $origin['start_time']) . "</font> 
                                >结束时间：<font color=\"comment\">" . date('Y-m-d H:i', $origin['end_time']) . "</font> 
                                >共计天数：<font color=\"comment\">{$origin['day']}</font> 
                                >请假事由：<font color=\"warning\">{$origin['explain']}</font> 
                                >
                                >请您知悉。
                "
            ];

            $_res = \fast\Http::post(self::$baseUrl . "cgi-bin/message/send?access_token=" . Wework::getAppAccessToken($appname), json_encode($msg));
            $res = json_decode($_res, true);
            return $res;
        }
    }


    public static function sendStudentLeaveNews($touser, $title, $info, $production_id, $origin_id, $appname)
    {

        $origin = Db::name('student_leave')->where('id', $origin_id)->find();
        $school = Db::name('config')->where('group', 'school')->column('name,value');
        if ($school['student_leave_warning'] == '-1') {
            return;
        }
        if (isset($school['student_leave_warning']) && $school['student_leave_warning'] <= $origin['day']) {
            $confg = config("wework.{$appname}");
            $username = Db::name('student_user')->where('id', $production_id)->value('username');

            $push = Db::name('config')->where('name', 'student_leave_warning_push')->value('value');
            $touser = Db::name('user')->where('id', 'in', $push)->column('UserId');
            if (!$touser) {
                return;
            }


            foreach ($touser as $key => $user) {
                $msg = [
                    'touser' => $user,
                    'msgtype' => 'markdown',
                    'agentid' => $confg['AgentId'],
                    'markdown' => [
                        'content' => "`学生请假消息预警`
                                    >**事项详情** 
                                    >人员姓名：<font color=\"info\">{$username}</font> 
                                    >开始时间：<font color=\"comment\">" . date('Y-m-d H:i', $origin['start_time']) . "</font> 
                                    >结束时间：<font color=\"comment\">" . date('Y-m-d H:i', $origin['end_time']) . "</font> 
                                    >共计天数：<font color=\"comment\">{$origin['day']}</font> 
                                    >请假事由：<font color=\"warning\">{$origin['explain']}</font> 
                                    >
                                    >请您知悉。"
                    ]

                ];

                $_res = \fast\Http::post(self::$baseUrl . "cgi-bin/message/send?access_token=" . Wework::getAppAccessToken($appname), json_encode($msg));
                $res = json_decode($_res, true);
            }
            return $res;
        }
    }


    /*
    * 给家长推送奖惩消息
    * $touser 学生ID
    * $info 内容
    * $production_id 记录人ID
    */
    public static function sendJiazhangText($touser, $info, $production_id)
    {
        $appname = 'jiaxiaogoutong';//家校沟通
        $confg = config("wework.{$appname}");
        $date = date('Y-m-d H:i');
        $username = Db::name('user')->where('id', $production_id)->value('username');//查询记录人名字
        $name = Db::name('student_user')->where('id', $touser)->value('username');//查询学生名字
        $touser = Db::name('student_parent')->where('student_userid', 'in', $touser)->column('wechat_student_userid');//查询企业微信学生ID
        foreach ($touser as $key => $user) {
            $msg = [
                'to_student_userid' => $user,//接收人ID
                'msgtype' => 'text',//文本消息
                'agentid' => $confg['AgentId'],
                'text' => [
                    'content' => "标题：奖惩消息\n事由：{$info}.\n学生名字：{$name}.\n时间：{$date}\n记录人：{$username}",
                ]
            ];

            $_res = \fast\Http::post(self::$baseUrl . "cgi-bin/externalcontact/message/send?access_token=" . Wework::getAppAccessToken($appname), json_encode($msg, JSON_UNESCAPED_UNICODE));
            $res = json_decode($_res, true);
        }
    }

    /*
    * 给家长推送导师制消息
    * $touser 学生ID
    * $name 学生名字
    * $info 内容
    * $production_id 记录人ID
    * $id 表ID
    */
    public static function sendDaoshiText($touser, $name, $info, $production_id, $id)
    {
        $appname = 'jiaxiaogoutong';//家校沟通
        $confg = config("wework.{$appname}");
        $date = date('Y-m-d H:i');
        $username = Db::name('user')->where('id', $production_id)->value('username');//查询记录人名字
        $touser = Db::name('student_parent')->where('student_userid', 'in', $touser)->column('wechat_student_userid');//查询企业微信学生ID
        $http_type = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')) ? 'https://' : 'http://';

        foreach ($touser as $key => $user) {
            $msg = [
                "to_student_userid" => $user,//发给学生的所有家长（最多支持1000个）
                "msgtype" => "news",
                "agentid" => $confg['AgentId'],
                "news" => [
                    "articles" => [[
                        "title" => "谈话辅导消息",
                        "description" => "评语：{$info}\n学生名字：{$name}\n导师：{$username}\n时间：{$date}\n查看详情",
                        "url" => $http_type . $_SERVER['SERVER_NAME'] . '/parents/#/pages/tutor/details?id=' . $id,
                        "picurl" => ""//图片
                    ]]
                ]
            ];

            //https://qyapi.weixin.qq.com/cgi-bin/externalcontact/message/send?access_token=ACCESS_TOKEN
            $_res = \fast\Http::post(self::$baseUrl . "cgi-bin/externalcontact/message/send?access_token=" . Wework::getAppAccessToken($appname), json_encode($msg, JSON_UNESCAPED_UNICODE));
            $res = json_decode($_res, true);
        }
    }

    //*********************************发送通知 handle end*******************************************************//


    //通讯录成员变更事件（非家校通讯录）
    public function bookUser($info)
    {
        if (!isset($info['ChangeType'])) {
            return '未识别的消息类型';
        }

        if ($info['ChangeType'] == 'create_user' || $info['ChangeType'] == 'update_user') {
            $user = Db::name('user')->where('UserId', $info['UserID'])->find();
            if ($user) {
                $data['updatetime'] = time();

                if (isset($info['Name'])){
                    $data['username'] = $info['Name'];
                    $data['nickname'] = $info['Name'];
                }

                if (isset($info['Gender'])){
                    $data['gender'] = $info['Gender'];
                }
                if (isset($info['Mobile'])){
                    $data['mobile'] = $info['Mobile'];
                }
                if (isset($info['Avatar'])){
                    $data['avatar'] = $info['Avatar'];
                }

                Db::name('user')->where('id',$user['id'])->update($data);
                $user_id = $user['id'];

                if (isset($info['Department'])){
                    Db::name('school_department_relation')->where('user_id',$user['id'])->delete();
                }

            } else {
                $data = [
                    'school_campus_id' => campus_id(1),
                    'group_id' => 14,
                    'username' => $info['Name'],
                    'nickname' => $info['Name'],
                    'gender' => $info['Gender'],
                    'password' => '99d7db228a2f27a2ceaae81f42f8e73b',
                    'salt' => 'fZetmE',
                    'mobile' => $info['Mobile'] ?? '',
                    'avatar' => $info['Avatar'] ?? '',
                    'status' => 'normal',
                    'UserId' => $info['UserID'],
                    'origin_info' => '2',
                    'jointime' => time(),
                    'createtime' => $info['CreateTime'],
                ];
                $user_id = Db::name('user')->insertGetId($data);
            }

            $department_relation = [];
            if (!empty($info['Department'])) {
                $Department = explode(',', $info['Department']);

                if (!empty($info['IsLeaderInDept'])) {
                    $IsLeaderInDept = explode(',', $info['IsLeaderInDept']);
                } else {
                    $IsLeaderInDept = [];
                    $IsLeaderInDept = array_pad($IsLeaderInDept, 2,0);
                }
                $department_id = Db::name('school_department')->where(['wechat_id'=>['in',$Department]])->column('wechat_id,id');
                $Department = array_combine($Department,$IsLeaderInDept);
                foreach ($Department as $k => $v){
                    if (isset($department_id[$k])){
                        $department_relation[] = [
                            'department_id'     => $department_id[$k],
                            'user_id'           => $user_id,
                            'school_campus_id'  => campus_id(1),
                            'year_id'           => year_id(1),
                            'semester_id'       => semester_id(1),
                            'createtime'        => time(),
                            'wechat_dep_id'     => $k,
                            'wechat_user_id'    => $info['UserID'],
                            'department_lead'   => $v
                        ];
                    }
                }
            }
            if ($department_relation){
                Db::name('school_department_relation')->insertAll($department_relation);
            }
        }elseif($info['ChangeType'] == 'delete_user'){
            $user = Db::name('user')->where('UserId', $info['UserID'])->find();
            if ($user){
                Db::name('user')->where('UserId', $info['UserID'])->delete();
                Db::name('school_department_relation')->where('UserId',$info['UserID'])->delete();
            }
        }elseif($info['ChangeType'] == 'create_party' || $info['ChangeType'] == 'update_party'){
            $department = Db::name('school_department')->where('wechat_id', $info['Id'])->find();
            $ParentId = 0;
            if (isset($info['ParentId']) && $info['ParentId'] > 0){
                $ParentId = (int) Db::name('school_department')->where('wechat_id', $info['ParentId'])->value('id');
            }

            if ($department){
                if (isset($info['Name'])){
                    $data['name'] = $info['Name'];
                }
                $data['pid'] = $ParentId;
                $data['updatetime'] = time();

                Db::name('school_department')->where('id',$department['id'])->update($data);
            }else{
                $data = [
                    'createtime'        =>time(),
                    'pid'               =>$ParentId,
                    'school_campus_id'  =>campus_id(1),
                    'name'              =>$info['Name'],
                    'wechat_id'         =>$info['Id']
                ];
                Db::name('school_department')->insert($data);
            }

        }elseif($info['ChangeType'] == 'delete_party'){
            $department = Db::name('school_department')->where('wechat_id', $info['Id'])->find();
            if ($department){
                Db::name('school_department')->where('id', $department['id'])->delete();
                Db::name('school_department_relation')->where('department_id',$department['id'])->delete();
            }
        }


    }
}